/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dieci.reports;

import java.sql.Connection;
import java.util.Map;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.hibernate.Session;

/**
 *
 * @author patobl
 */
public class JasperReportRunner {

    String report_file;
    Session session;
    Map parameters;
    
    public JasperReportRunner(String report_file, Session session, Map parameters) 
    {
        this.report_file = report_file;
        this.session = session;
        this.parameters = parameters;
    }

    public void run() throws Exception
    {
        try 
        {
            if (report_file == null) 
            {
                throw new Exception("No se pudo generar el reporte. No se encuentra el archivo");
            }

            JasperReport masterReport = (JasperReport) JRLoader.loadObjectFromFile(report_file);
            JasperReport subReport = null;
            if(!parameters.isEmpty())
            {
                if(parameters.containsKey("TotalVentas.jasper"))
                {
                    subReport = (JasperReport) JRLoader.loadObjectFromFile((String)parameters.get("TotalVentas.jasper"));
                }
            }
            
            session.beginTransaction();
            
            if(session.isOpen() && session.isConnected())
            {
                Connection connection = session.connection();
            
                JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, parameters, connection);
            
                JasperViewer jviewer = new JasperViewer(jasperPrint, false);
                jviewer.setTitle("Reporte");
                jviewer.setVisible(true);
            }
            else
            {
                throw new Exception("Session is not opened");
            }
        } 
        catch (Exception j) 
        {
            throw new Exception("No se pudo generar el reporte. "+j.getMessage());
        }
    }
}
